<template>
    <div class="map">
        <el-dialog
			class="sys-admin-dialog"
			width="70%" 
			:visible="showMap"
			@close="dialogClose"
		    >
            <div id="wrap">
        <div id="searchWrap">
            <div class="searchWrap">
                <input type="text" v-model="address" @input="search"><button @click="search">搜索</button>
            </div>
            <div id="result" class="amap_lib_placeSearch" v-show="hide">
                <div class="amap_lib_placeSearch_list amap-pl-pc"  v-for="(item,index) in poiArr"
                    @click="openMarkerTipById(index,$event)"
                    @mouseout="onmouseout_MarkerStyle(index+1,$event)"
                    :key="index">
                    <div class="poibox" style="border-bottom: 1px solid #eaeaea">
                        <div class="amap_lib_placeSearch_poi poibox-icon" :class="index==selectedIndex?'selected':''">{{index+1}}</div>
                        <div class="poi-img" v-if="item.url" :style="'background-image:url('+item.url+'?operate=merge&amp;w=90&amp;h=56&amp;position=5)'"
                        ></div>
                        <h3 class="poi-title" >
                            <span class="poi-name">{{item.name}}</span>
                        </h3>
                        <div class="poi-info">
                            <p class="poi-addr">地址：{{item.address}}</p>
                            <p class="poi-tel">电话：{{item.tel}}</p>
                        </div>
                        <div class="clear"></div>
                    </div>
                </div>
            </div>
        </div>
        <div id="iCenter"></div>
        <span v-html="mapStyle"></span>
    </div>
        <div style="text-align:center;margin-top:20px;">
            <el-button size="mini" type="primary" @click="saveLocal">保存</el-button>
            <el-button size="mini" type="primary" @click="dialogClose">取消</el-button>
        </div>
        </el-dialog>
    </div>
</template>

<script>
  export default {
    props:['showMap', 'local'],// 父组件传过来的地址和地址经纬度信息，
    data() {
      return {
        mapStyle: `
            <style>
                #searchWrap input{
                    width: 220px !important;
                    height: 28px !important;
                }
                #searchWrap button{
                    width: 79px !important;
                }
             </style>
        `,
        address:'',//保存地址的汉字名字
        map1: '',
        map:'',//保存地址的经纬度
        poiArr: [],//左边搜索出来的数组
        windowsArr: [],//信息窗口的数组
        marker: [],
        mapObj: "",//地图对象
        selectedIndex: -1,
        hide: false,
        clickType: 1,
        location:{
          
        }
      };
    },
    mounted() {
      
    },
    methods: {
        saveLocal () {
            if (!this.address) {
                this.$emit('cancel')
                return;
            };
            this.$confirm('确定把当前地址切换为' + this.address + '？')
            .then(_ => {
                console.log(this.location, 'this.location')
                this.$emit('setLocal', this.location, this.address)
        
            })
            .catch(_ => {});
        },
        dialogClose () {
            this.$emit('cancel')
        },
        showToast(address){
            this.placeSearch(address.address)
            this.location.P =address.lat
            this.location.Q =address.lng
            this.address = address.address
            let that = this;
            new AMap.InfoWindow({
            content:"<h3>" + '当前选中地址' + "</h3>" + that.address,
            size: new AMap.Size(300, 0),
            autoMove: true,
            offset: new AMap.Pixel(-4, -10)
            }).open(that.mapObj,that.location)
        },
        cancelSave(){
            eventBus.$emit('cancelSave')
        },
        saveAddress(){
            let addressName,location;
            if(this.clickType==1){
            let address = this.poiArr[this.selectedIndex]
            addressName = address.name+address.address;
            location = address.location;

            }else if(this.clickType==2){
            addressName = this.address;
            location = this.map;
            }else if(this.clickType==3){
            addressName = this.address;
            location = this.map1;
            }
            eventBus.$emit('saveAddress',[addressName,location])
        },
        // 经纬度转化为详细地址
        getAddress(){
            let that = this;
            AMap.plugin('AMap.Geocoder', () => {
                let geocoder = new AMap.Geocoder({
                    radius: 100,
                    extensions: "all"
                });
                geocoder.getAddress([that.map1.lng,that.map1.lat], (status, result) => {
                    if (status === 'complete' && result.info === 'OK') {
                        let address = result.regeocode.formattedAddress,
                            length = result.regeocode.pois.length;
                        that.address = result.regeocode.formattedAddress;
                        this.location.P = that.map1.lng;
                        this.location.Q = that.map1.lat;
                        console.log(result.regeocode, 'result.regeocode.pois')
                    }
                });
            })
        },
        // 地图点击事件
        testevent(){
            let that = this;
            this.clickType = 3
            // var map=new AMap.Map('iCenter');//重新new出一个对象，传入参数是div的id
            AMap.event.addListener(this.mapObj,'click',function (e) { //添加点击事件,传入对象名，事件名，回调函数
                console.log(e, 'eeeeeeeee')
                that.map1 = e.lnglat;
                that.getAddress();
                setTimeout(()=>{
                    new AMap.InfoWindow({
                        content:"<h3>" + '当前选中地址' + "</h3>" + that.address,
                        size: new AMap.Size(300, 0),
                        autoMove: true,
                        offset: new AMap.Pixel(-4, -10)
                    }).open(that.mapObj,e.lnglat)
                },100)
            })
        },
        //创建一个map
        mapInit() { 
            // 判断该设备是否定位过
            // 如果没有则获取当前位置
            console.log(!this.local.P, '!this.local.P')
            if (!this.local.P) {
                this.mapObj = new AMap.Map("iCenter", {
                    resizeEnable: true,
                    zoom: 10,
                })
                this.location = {
                    P: undefined,
                    Q: undefined
                };
                //获取当前定位
                AMap.plugin('AMap.Geolocation', () => {
                    var geolocation = new AMap.Geolocation({
                        enableHighAccuracy: true,//是否使用高精度定位，默认:true
                        timeout: 10000,          //超过10秒后停止定位，默认：5s
                        buttonPosition:'RB',    //定位按钮的停靠位置
                        buttonOffset: new AMap.Pixel(10, 20),//定位按钮与设置的停靠位置的偏移量，默认：Pixel(10, 20)
                        zoomToAccuracy: true,   //定位成功后是否自动调整地图视野到定位点

                    });
                    this.mapObj.addControl(geolocation);
                    geolocation.getCurrentPosition((status,result) => {
                        console.log(status,result, 'status,result')
                        if(status=='complete'){
                            console.log(this.location, result.position.lng, '11')
                            this.location.P = result.position.lng;
                            this.location.Q = result.position.lat;
                             // 创建一个 Icon
                            var startIcon = new AMap.Icon({
                                // 图标尺寸
                                size: new AMap.Size(19, 33),
                                // 图标的取图地址
                                image: 'https://webapi.amap.com/theme/v1.3/markers/b/mark_bs.png',
                                // 图标所用图片大小
                                imageSize: new AMap.Size(19, 33),
                                // 图标取图偏移量
                                imageOffset: new AMap.Pixel(0, 0)
                            });
                            // 实例化点标记
                            let marker = new AMap.Marker({
                                    icon: startIcon,
                                    position: [this.location.P, this.location.Q],
                                    offset: new AMap.Pixel(-13, -30)
                                });
                            marker.on('click', (e) => {
                                // infoWindow.setContent(e.target.content);
                                // infoWindow.open(map, e.target.getPosition());
                                this.location.P = e.target.getPosition().lng;
                                this.location.Q = e.target.getPosition().lat;
                            });
                            marker.emit('click', {target: marker});
                            marker.setMap(this.mapObj);
                            this.testevent();
                            return;
                            
                        }else{
                            this.$message({
                                type: 'info',
                                message: '定位失败'
                            })
                            return;
                        }
                    });
                });
            } else {
                this.mapObj = new AMap.Map("iCenter", {
                    resizeEnable: true,
                    center: [this.local.P, this.local.Q],
                    zoom: 10,
                })
                // 创建一个 Icon
                var startIcon = new AMap.Icon({
                    // 图标尺寸
                    size: new AMap.Size(19, 33),
                    // 图标的取图地址
                    image: 'https://webapi.amap.com/theme/v1.3/markers/b/mark_bs.png',
                    // 图标所用图片大小
                    imageSize: new AMap.Size(19, 33),
                    // 图标取图偏移量
                    imageOffset: new AMap.Pixel(0, 0)
                });
                // 实例化点标记
                let marker = new AMap.Marker({
                        icon: startIcon,
                        position: [this.location.P, this.location.Q],
                        offset: new AMap.Pixel(-13, -30)
                    });
                marker.on('click', (e) => {
                    // infoWindow.setContent(e.target.content);
                    // infoWindow.open(map, e.target.getPosition());
                    this.location.P = e.target.getPosition().lng;
                    this.location.Q = e.target.getPosition().lat;
                });
                marker.emit('click', {target: marker});
                marker.setMap(this.mapObj);
                this.testevent();
            }

            
        },
        //根据名字地址去搜索结果
        placeSearch(name) {
            let that = this;
            this.hide = true
            var MSearch;
            this.mapObj.plugin(
                ["AMap.PlaceSearch", "AMap.ToolBar", "AMap.Scale"],
                () => {
                    this.mapObj.addControl(new AMap.ToolBar())
                    this.mapObj.addControl(new AMap.Scale())
                    MSearch = new AMap.PlaceSearch({
                    //构造地点查询类
                        city: that.address //城市
                    });
                    AMap.event.addListener(MSearch,"complete",this.keywordSearch_CallBack) //返回地点查询结果
                    MSearch.search(name); //关键字查询
                }
            );
        },
        //结果的回调
        keywordSearch_CallBack(data) {
            console.log(data, 'data')
            var poiArr = data.poiList.pois
            var resultCount = poiArr.length
            this.poiArr = poiArr; //左边要渲染的数据
            for (var i = 0; i < resultCount; i++) {
                this.addmarker(i, poiArr[i])
                this.poiArr[i].url = this.poiArr[i].photos? this.poiArr[i].photos[0]? this.poiArr[i].photos[0].url: "": ""
            }
            this.mapObj.setFitView()
        },
        //添加marker&infowindow
        addmarker(i, d) {
            console.log(i, d)
            let lngX = d.location.getLng(),
                latY = d.location.getLat(),
                markerOption = {
                    map: this.mapObj,
                    position: new AMap.LngLat(lngX, latY)
                },
                mar = new AMap.Marker(markerOption);
            mar.on('click', (e) => {
                this.location.P = e.target.getPosition().lng;
                this.location.Q = e.target.getPosition().lat;
            });
            this.marker.push(new AMap.LngLat(lngX, latY));
            let infoWindow = new AMap.InfoWindow({
                content: "<h3>" +'当前选中位置：'+ d.name + "</h3>" + this.TipContents(d.name, d.address),
                size: new AMap.Size(300, 0),
                autoMove: true,
                offset: new AMap.Pixel(0, -30)
            });
            this.windowsArr.push(infoWindow);
            var _this = this;
            var aa = (e) => {
                this.clickType = 2
                var obj = mar.getPosition();
                this.map = obj //这里保存的地址经纬度
                this.address = d.name + d.address //这里保存的是地址名字
                console.log(this.address, 'this.address')
                infoWindow.open(_this.mapObj, obj);
            }
            AMap.event.addListener(mar, "click", aa)
        },
        TipContents(name, address) {
            //窗体内容
            if (
            name == "" ||
            name == "undefined" ||
            name == null ||
            name == " undefined" ||
            typeof name == "undefined"
            ) {
            type = "暂无";
            }
            if (
            address == "" ||
            address == "undefined" ||
            address == null ||
            address == " undefined" ||
            typeof address == "undefined"
            ) {
            address = "暂无";
            }
            var str = `地址：${address}`
            return str
        },
        openMarkerTipById(pointid, event) {
            //根据id 打开搜索结果点tip
            this.clickType = 1
            event.currentTarget.style.background = "#CAE1FF";
            this.selectedIndex = pointid;
            this.map1 = this.poiArr[pointid].location;
            this.address = this.poiArr[pointid].address + this.poiArr[pointid].name;
            this.location.P = this.poiArr[pointid].location.lng;
            this.location.Q = this.poiArr[pointid].location.lat;
            console.log(this.poiArr[pointid], 'this.location')
            this.windowsArr[pointid].open(this.mapObj, this.marker[pointid])
        },
        onmouseout_MarkerStyle(pointid, event) {
            //鼠标移开后点样式恢复
            event.currentTarget.style.background = ""
        },
        search() {
            this.windowsArr = []
            this.marker = []

            this.mapObj=''
            this.mapInit()
            this.placeSearch(this.address)
        }
    },
        watch: {
            showMap (cur) {
                if (cur) {
                    this.$nextTick(() => {
                        this.location = JSON.parse(JSON.stringify(this.local))
                        this.mapInit()
                        this.placeSearch(this.address)
                    })
                    
                }else {
                    this.address = '';
                    this.mapObj && this.mapObj.destroy()
                }
            },
            location: {
                handler (cur) {
                    console.log(cur, 'gengxin')
                },
                deep: true
            }
        },
    };
</script>
<<style lang="scss">
    #wrap{
        width:100%;
        display: flex;
        #iCenter {
            height: 600px;
            position: relative;
            display: flex;
            flex: 1;
        }
        #searchWrap{
            width:300px;
            position: relative;
            height:600px;
            .searchWrap{
                position: absolute;
                width:300px;
                z-index: 9;
                display: flex;
                align-items: center;
                input{
                    width:260px;
                    height:24px;
                }
                button{
                    width:36px;
                    height:28px;
                }
            }
            #result {
                width: 300px;
                position: absolute;
                top:30px;
                height: 570px;
                z-index: 8;
                overflow-y: scroll;
                border-right: 1px solid #ccc;
            }
        }
        .amap_lib_placeSearch {
            height: 100%;
            overflow-y: scroll;
            .poibox {
                border-bottom: 1px solid #eaeaea;
                cursor: pointer;
                padding: 5px 0 5px 10px;
                position: relative;
                min-height: 35px;
                .selected {
                    background-image: url(https://webapi.amap.com/theme/v1.3/markers/n/mark_r.png) !important;
                }
                &:hover {
                    background: #f6f6f6;
                }
                .poi-img {
                    float: right;
                    margin: 3px 8px 0;
                    width: 90px;
                    height: 56px;
                    overflow: hidden;
                }
                .poi-title {
                    margin-left: 25px;
                    font-size: 13px;
                    overflow: hidden;
                }
                .poi-info {
                    word-break: break-all;
                    margin: 0 0 0 25px;
                    overflow: hidden;
                    p {
                        color: #999;
                        font-family: Tahoma;
                        line-height: 20px;
                        font-size: 12px;
                    }
                }
                .poibox-icon {
                    margin-left: 7px;
                    margin-top: 4px;
                }
                .amap_lib_placeSearch_poi {
                    background: url(https://webapi.amap.com/theme/v1.3/markers/n/mark_b.png)
                    no-repeat;
                    height: 31px;
                    width: 19px;
                    cursor: pointer;
                    left: -1px;
                    text-align: center;
                    color: #fff;
                    font: 12px arial, simsun, sans-serif;
                    padding-top: 3px;
                    position: absolute;
                }
            }
        }
        .btn{
            position: fixed;
            bottom:20px;
            left:50%;
            padding:10px;
        }
    }
</style>